/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */

import { OhosLogger } from '../utils/log/ohos-logger';
import { CommonConst, ModuleConst } from '../const/common-const';
import { Json5Reader } from '@ohos/hvigor';
import path from 'path';
import { pathParamsOpt } from './dependency-tag-validate';
import { FileUtil } from '../utils/file-util';
import { configFileLoader } from '../utils/loader/config-file-loader';
import { DependencyEnum } from "../project/dependency/core/dependency-interface";

const log: OhosLogger = OhosLogger.getLogger('DependencyModuleVersionValidate');

/**
 * 查找需要修改的对象中配置的dependency
 *
 * @param ohPackageObj
 */
export function resolveJsonObjWithoutAtModule(ohPackageObj: any) {
    const dependencyKeys = [DependencyEnum.DEPENDENCIES, DependencyEnum.DYNAMIC_DEPENDENCIES, DependencyEnum.DEV_DEPENDENCIES].map(k => k.toString());
    for (const key in ohPackageObj) {
        if (!dependencyKeys.includes(key)) {
            continue;
        }
        for (const dependency in ohPackageObj[key]) {
            ohPackageObj[key][dependency] = resolveModuleVersion(ohPackageObj[key][dependency]);
        }
    }
    log.debug(`jsonObjWithoutAtModule ${JSON.stringify(ohPackageObj)}`);
}


/**
 * 检测是否配置了@module格式的源码依赖，如果找到了则返回对应的版本号
 *
 * @param originalVersion 原始配置的参数
 * @private
 */
export function resolveModuleVersion(originalVersion: string):string {
    const moduleMatch = originalVersion.match(ModuleConst.REGEX);
    // 如果配置了@module的格式的源码依赖, 则读取build-profile的配置找到源码依赖的路径
    // 如果是非@module, 直接返回
    if (!moduleMatch) {
        return originalVersion;
    }
    const localModuleName = moduleMatch[1];
    let localModulePath = '';

    const buildProfileObj = configFileLoader.getConfigFileJson(path.resolve(process.cwd(), CommonConst.PROFILE_JSON5)) ?? {};

    if (!buildProfileObj.modules) {
        return originalVersion;
    }
    for (const module of buildProfileObj.modules) {
        if (localModuleName === module.name) {
            localModulePath = FileUtil.convertToAbsolutePath(module.srcPath, process.cwd());
        }
    }
    if (localModulePath !== '') {
        // 找到了依赖的源码路径
        // 查找对应oh-package.json5中配置的version
        const localModuleOhPackagePath = path.resolve(localModulePath, CommonConst.OH_PACKAGE_JSON5);
        const localModuleOhPackageObj =  configFileLoader.getConfigFileJson(localModuleOhPackagePath);
        return getParameterVersion(localModuleOhPackageObj.version, localModuleOhPackagePath);
    } else {
        log.printErrorExit('MODULE_DEPENDENCY_KEY_ERROR', [localModuleName, path.resolve(process.cwd(), CommonConst.OH_PACKAGE_JSON5)]);
    }
    return originalVersion;
}

function getParameterVersion(originalVersion: string, ohPackagePath: string):string {
    const projectOhPackageObj = Json5Reader.getJson5Obj(path.resolve(process.cwd(), CommonConst.OH_PACKAGE_JSON5));
    const parameterFilePath = projectOhPackageObj.parameterFile;
    if (parameterFilePath) {
        const pathParamsObj: pathParamsOpt = {
            parameterFilePath: parameterFilePath,
            ohPackageFilePath: ohPackagePath,
        }
        const parameterFileObj = Json5Reader.getJson5Obj(parameterFilePath);
        return FileUtil.extracted(originalVersion, parameterFileObj, pathParamsObj)
    }
    return originalVersion;
}
